package growth.net.p2p;


import java.net.InetAddress;

public class ReqPro {

    public void addNeighbour(String name, int listPort, int sendPort,
            InetAddress ip) throws Exception {
        Neighbour newNeighbour = new Neighbour();
        newNeighbour.name = name;
        newNeighbour.ip = ip;
        newNeighbour.listPort = listPort;
        newNeighbour.sendPort = sendPort;
        PeerData.neighboursList.add(newNeighbour);
        SendingService.getSendingService().send(
                PeerData.ACKNOWLEDGE + "ADDED AS NEIGHBOUR", ip, listPort);
    }

    public void processMessage(String inMsg) throws Exception {
        String[] partsOfMsg = inMsg.trim().split(",");
        if (partsOfMsg[0].equals(PeerData.ADDMEREQUEST)) {            
            for(int i = 0;i<PeerData.neighboursList.size(); i++)
            {
                if(partsOfMsg[1].toString().equals(PeerData.neighboursList.get(i).name)){
                    System.out.println("Already in the list");
                    return;
                }
            }
            Neighbour neighbour = new Neighbour();
            neighbour.name = partsOfMsg[1];
            neighbour.listPort = Integer.parseInt(partsOfMsg[2].trim());
            neighbour.sendPort = Integer.parseInt(partsOfMsg[3].trim());
            String[] splitAdd = partsOfMsg[4].trim().split("/");
            neighbour.ip = InetAddress.getByName(splitAdd[1]);
            PeerData.neighboursList.add(neighbour);
            SendingService.getSendingService().send(
                    PeerData.ACKNOWLEDGE + ", ADDED BY " + PeerData.myName,
                    neighbour.ip, neighbour.listPort);
        } else if (partsOfMsg[0].equals(PeerData.MESSAGE)) {
        	System.out.println(inMsg);
			String msgAck = PeerData.ACKNOWLEDGE+","+"MESSAGE RECEIVED BY"+PeerData.myName;
			
			for (Neighbour nbr : PeerData.neighboursList) {
				if (nbr.name.equals(partsOfMsg[2])) {
					
				}
					SendingService.getSendingService().send(msgAck, nbr.ip,
							nbr.listPort);
				}
        } else if (partsOfMsg[0].equals(PeerData.REPLACEMENT)) {
            Neighbour repNeighbour = new Neighbour();
            repNeighbour.name = partsOfMsg[2];
            repNeighbour.listPort = Integer.parseInt(partsOfMsg[3].trim());
            repNeighbour.sendPort = Integer.parseInt(partsOfMsg[4].trim());
            String[] splitAdd = partsOfMsg[5].trim().split("/");
            repNeighbour.ip = InetAddress.getByName(splitAdd[1]);
            for (Neighbour nbr : PeerData.neighboursList) {
                if (nbr.name.equals(partsOfMsg[1])) {
                    PeerData.neighboursList.remove(nbr);
                    PeerData.neighboursList.add(repNeighbour);
                }
            }
            System.out.println("REPLACED " + partsOfMsg[1] + " WITH "
                    + repNeighbour.name);
        } else if (partsOfMsg[0].equals(PeerData.SEARCH)) {
        } else if (partsOfMsg[0].equals(PeerData.DELETEME)) {
            System.out.println("Received DELETE_ME from " + partsOfMsg[0].toString());
            int indexToDelete = -1;
//            System.out.println("Searching for node: " + partsOfMsg[1]);
            for (Neighbour nbr : PeerData.neighboursList) {
                if (nbr.name.toString().equals(partsOfMsg[1].toString().trim())) {
                    indexToDelete = PeerData.neighboursList.indexOf(nbr);
                }

            }
            if (indexToDelete > -1) {
                PeerData.neighboursList.remove(indexToDelete);
                System.out.println("DELETE " + partsOfMsg[0].toString());
            } else {
                System.out.println("indexToDelete: " + indexToDelete);
                System.out.println("DELETE Failed: Node not found");
            }
        }

    }

    public void sendReplaceMeWith(Neighbour repNbr, Neighbour withNbr)
            throws Exception {
        System.out.println("rep" + repNbr.ip);
        String reqMsg = PeerData.REPLACEMENT + "," + PeerData.myName + ","
                + repNbr.name + "," + repNbr.listPort + "," + repNbr.sendPort
                + "," + repNbr.ip;
        SendingService.getSendingService().send(reqMsg, withNbr.ip,
                withNbr.listPort);
    }

    public void sendAddMeRequest(String name, int lisPost, int sendPort,
            InetAddress ip, int peerLisPort, InetAddress peerAdd)
            throws Exception {
        String message = PeerData.ADDMEREQUEST + "," + name + "," + lisPost
                + "," + sendPort + "," + ip;
        SendingService.getSendingService().send(message, peerAdd, peerLisPort);
    }

    public void sendMessage(String to, String msg) throws Exception {
        for (Neighbour nbr : PeerData.neighboursList) {
            if (nbr.name.equals(to)) {
                String msgStr = PeerData.MESSAGE + "," + msg + " from "
                        + PeerData.myName;
                SendingService.getSendingService().send(msgStr, nbr.ip,
                        nbr.listPort);
            }
        }

    }

    public void sendDeleteMeForever(Neighbour parent)
            throws Exception {
        System.out.println("Sending DELETEME to " + parent.name);
        String reqMsg = PeerData.DELETEME + "," + PeerData.myName;
        SendingService.getSendingService().send(reqMsg, parent.ip,
                parent.listPort);
    }

//    public void sendReplacementsToAll() throws Exception {
//        if (1 == PeerData.neighboursList.size()) {
//            System.out.println("Only connected to 1 node");
//            this.sendDeleteMeForever(PeerData.neighboursList.get(0));
//            return;
//        }
//        for (int i = 0; i < PeerData.neighboursList.size(); i++) {
//            if (i == (PeerData.neighboursList.size() - 1)) {
//                System.out.println(PeerData.neighboursList.get(i).name + " Replacing " + PeerData.myName + " with " + PeerData.neighboursList.get(0).name);
//                this.sendReplaceMeWith(PeerData.neighboursList.get(i), PeerData.neighboursList.get(0));
//                this.sendReplaceMeWith(PeerData.neighboursList.get(0), PeerData.neighboursList.get(i));
//            } else {
//                System.out.println(PeerData.neighboursList.get(i).name + " Replacing " + PeerData.myName + " with " + PeerData.neighboursList.get(i + 1).name);
//                this.sendReplaceMeWith(PeerData.neighboursList.get(i), PeerData.neighboursList.get(i + 1));
//                this.sendReplaceMeWith(PeerData.neighboursList.get(i + 1), PeerData.neighboursList.get(i));
//            }
//        }
//    }
    public void sendAddToList(Neighbour nodeInfo, Neighbour rcvrNode)
            throws Exception {
//        System.out.println("rep" + nodeInfo.ip);
//        String message = PeerData.ADDMEREQUEST + "," + name + "," + lisPost
//                + "," + sendPort + "," + ip;
        String reqMsg = PeerData.ADDMEREQUEST + "," + nodeInfo.name + "," + nodeInfo.listPort
                + "," + nodeInfo.sendPort + "," + nodeInfo.ip;
        SendingService.getSendingService().send(reqMsg, rcvrNode.ip,
                rcvrNode.listPort);
    }

    public void sendBroadcastToAll() throws Exception {
        if (1 == PeerData.neighboursList.size()) {
//            System.out.println("Only connected to 1 node");
            this.sendDeleteMeForever(PeerData.neighboursList.get(0));
            return;
        }
        for (int i = 0; i < PeerData.neighboursList.size(); i++) {
            for (int j = 0; j < PeerData.neighboursList.size(); j++) {
                if (i != j) {
//                    System.out.println("i: " + i + " j: " + j);
//                    System.out.println("About: " + PeerData.neighboursList.get(i).name + " Telling to: " + PeerData.neighboursList.get(j).name);
                    this.sendAddToList(PeerData.neighboursList.get(j), PeerData.neighboursList.get(i));
                }
            }
        }
        for (int i = 0; i < PeerData.neighboursList.size(); i++) {
            this.sendDeleteMeForever(PeerData.neighboursList.get(i));
        }
//        if (i == (PeerData.neighboursList.size() - 1)) {
//            System.out.println(PeerData.neighboursList.get(i).name + " Replacing " + PeerData.myName + " with " + PeerData.neighboursList.get(0).name);
//            this.sendReplaceMeWith(PeerData.neighboursList.get(i), PeerData.neighboursList.get(0));
//            this.sendReplaceMeWith(PeerData.neighboursList.get(0), PeerData.neighboursList.get(i));
//        } else {
//            System.out.println(PeerData.neighboursList.get(i).name + " Replacing " + PeerData.myName + " with " + PeerData.neighboursList.get(i + 1).name);
//            this.sendReplaceMeWith(PeerData.neighboursList.get(i), PeerData.neighboursList.get(i + 1));
//            this.sendReplaceMeWith(PeerData.neighboursList.get(i + 1), PeerData.neighboursList.get(i));
//        }

    }
}
